package com.example.vip31;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.vip31.utils.LogUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *  https://github.com/bumptech/glide     https://muyangmin.github.io/glide-docs-cn/
 *
 * glide源码分析--生命周期 1
 *
 * Glide使用及原理分析
 * https://blog.csdn.net/java521666/article/details/125968974
 *
 *  Glide缓存机制原理详解
 *  https://www.easemob.com/news/7095
 *
 *  https://www.jianshu.com/p/e99b40ccaf9b
 *
 *  https://blog.csdn.net/qq_32677531/article/details/126257189
 */
public class MainActivity extends AppCompatActivity {
    private ImageView mImageView;
    private TextView tv_load;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.i("activity 生命周期 onCreate");

        setContentView(R.layout.activity_main);
        tv_load = findViewById(R.id.tv_load);
        mImageView = findViewById(R.id.img);

        FragmentManager supportFragmentManager = getSupportFragmentManager();
        supportFragmentManager.beginTransaction().replace(android.R.id.content,new Fragment1()).commit();


        ExecutorService executorService = Executors.newFixedThreadPool(1);
        tv_load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String url = "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";
//                Bitmap bitmap = getBitmap(url);
//                mImageView.setImageBitmap(bitmap);
                //android.os.NetworkOnMainThreadException
                //        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1460)
                //        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
                //        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
                //        at java.net.InetAddress.getAllByName(InetAddress.java:787)
                //        at com.android.okhttp.Dns$1.lookup(Dns.java:39)

                Glide.with(MainActivity.this).load(url).into(mImageView);

                //注意：Glide需要用到的context，一定要是当前activity的，不能是application否则导致内内存过大

                /*
                    三大主线 with 、load 、into


                    with:
                        创建 RequestManager，RequestManagerRetriever —> 调用 getSupportRequestManagerFragment 方法 创建 SupportRequestManagerFragment
                        在创建 SupportRequestManagerFragment 前，先从缓存里检测是否存在 SupportRequestManagerFragment， 如果有直接返回


                        SupportRequestManagerFragment 是 无UI的Fragment，传到Activity上，并将这个Fragment的生命周期绑定到RequestManager上，即 RequestManager能够管理生命周期

                        把生命周期方法j进行关联
                    load:
                        构建RequestBuilder对象，把Url传进去

                    into:
                        活动缓存（Hashmap）（弱引用缓存）,根据EngineKey去活动缓存中获取数据

                        内存缓存（Lru算法）

                        磁盘缓存（Lru算法）


                        调用 RequestBuilder类里的 obtainRequest方法 通过返回 调用 SingleRequest.obtain 返回 Request

                        SingleRequest.begin方法里调用  target.onLoadStarted(getPlaceholderDrawable());

                        当RequestManager类里调用requestTracker.runRequest 的时候，所有请求都会构成一个SingleRequest，并开始调用begin方法运行
                        begin方法最终会调用engine.load方法
                        根据request构建EngineKey


                        根据EngineKey去活动缓存中获取数据
                        如果获取不到，去内存缓存中获取数据
                        如果获取不到，通过硬盘缓存的线程池去获取本地硬盘的数据
                        如果获取不到本地的，通过网络的线程池去获取网络的数据




                 */

                /*
                    重要类
                    Engine

                    glide 实现ComponentCallbacks
                    activity也实现ComponentCallbacks
                    ComponentCallbacks接口


                     glide怎么监听网络变化的？
                     DefaultConnectivityMonitor 注册register 网络广播

                    RequestTracker里的restartRequests 重新请求


                     glide怎么切换线程的？
                     Handel


                     glide为什么缓存fragment？
                     只保留一个fragment



                 */

//                executorService.submit(new Runnable() {
//                    @Override
//                    public void run() {
//                        Bitmap bitmap = getBitmap(url);
//                        runOnUiThread(new Runnable() {//线程切换
//                            @Override
//                            public void run() {
//                                mImageView.setImageBitmap(bitmap);
//                            }
//                        });
//                    }
//                });
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtil.i("activity 生命周期 onStart");

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtil.i("activity 生命周期 onRestart");

    }

//    @Override
//    protected void onPostResume() {
//        super.onPostResume();
//        LogUtil.i("activity 生命周期 onPostResume");
//
//    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.i("activity 生命周期 onResume");

    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtil.i("activity 生命周期 onPause");

    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtil.i("activity 生命周期 onStop");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.i("activity 生命周期 onDestroy");
    }

    private Bitmap getBitmap(String url) {
        Bitmap bitmap = null;
        try {
            URL imgUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(2500);
            conn.setConnectTimeout(2500);
            //HttpUrlConnection的setDoOutput与setDoInput的区别  https://blog.csdn.net/u010665691/article/details/45558119
            conn.setDoInput(true);
            conn.connect();
            int contentLength = conn.getContentLength();//文件大小
            InputStream inputStream = conn.getInputStream();

            bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bitmap;
    }
}